/* eslint-disable max-lines */
/* eslint-disable react/jsx-max-depth */
import React, { useEffect, useState, useRef, useCallback } from 'react';
import { connect, useDispatch, history } from 'umi';
import {
  Input,
  Button,
  Divider,
  Form,
  Select,
  Dropdown,
  Menu,
  Table,
  Popconfirm,
  message,
  Spin,
  Row,
  Col,
} from 'antd';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import PageTopFormContent from '@/components/PageTopFormContent';
import PaginationCommon from '@/components/PaginationCommon';
import Tree from '@/components/Tree';
import Ellipsis from '@/components/Ellipsis';
import { ORG_TYPE_LIST } from '@/utils/const';
import useEnum from '@/hooks/useEnum';
import OrgAddEdit from './components/OrgAddEdit';
import PositionManage from './components/PositionManage';
import styles from './OrgManage.less';

// 首先我们先定义个数组，用来保存路径节点id
let nodePathArray = [];

// (tree为目标树，targetId为目标节点id)
function getNodeRoute(tree, targetId) {
  for (let index = 0; index < tree.length; index++) {
    if (tree[index].children) {
      const endRecursiveLoop = getNodeRoute(tree[index].children, targetId);
      if (endRecursiveLoop) {
        nodePathArray.push(tree[index].title);
        return true;
      }
    }
    if (tree[index].id === targetId) {
      nodePathArray.push(tree[index].title);
      return true;
    }
  }
  return false;
}

let allTreeData = [];

const OrgManage = (props) => {
  const {
    orgManageModel,
    loading: { effects },
  } = props;
  const { orgSelectList, orgSelectListTotal } = orgManageModel;

  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };

  const [currentPageNum, setcurrentPageNum] = useState(1);
  const [currenPageSize] = useState(10);
  const [currentSelectedOrgData, setCurrentSelectedOrgData] = useState({});
  const [currentEditData, setCurrentEditData] = useState({});
  const [posManageOrgId, setPosManageOrgId] = useState();
  const [orgNameInput] = useState('');
  // 组织新增操作，在该id下新建组织
  const [orgAddOptParentId, setOrgAddOptParentId] = useState();
  const [orgPathList, setOrgPathList] = useState([]);
  const [positionVisible, setPositionVisible] = useState(false);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [drawerType, setDrawerType] = useState('add');
  const [treeData, setTreeData] = useState([]);
  const dispatch = useDispatch();
  const onTreeRef = useRef(null);
  const [form] = Form.useForm();
  // 数据来源字典编码 500
  const dataSourceEnum = useEnum('500');
  // 业务层级字典编码 600
  const businessLevelEnum = useEnum('600');
  // 部门分类字典编码 700
  const departmentClassificationEnum = useEnum('700');

  const getRootTree = useCallback(() => {
    dispatch({
      type: 'orgManageModel/getOrgRootTree',
    }).then((data) => {
      allTreeData = data;
      setTreeData(data);
      // if (data && data.length > 0) {
      //   setCurrentSelectedOrgData(data[0]);
      // }
    });
  }, [dispatch]);

  useEffect(() => {
    getRootTree();
    return () => {
      allTreeData = [];
    };
  }, [getRootTree]);

  const updateTableData = useCallback(() => {
    const currentData = {
      pageIndex: currentPageNum,
      pageSize: currenPageSize,
      parentId: currentSelectedOrgData.id,
      ...form.getFieldsValue(),
    };
    if (orgNameInput) {
      currentData.orgName = orgNameInput;
    }
    dispatch({
      type: 'orgManageModel/getOrgList',
      payload: currentData,
    });
  }, [currenPageSize, currentPageNum, currentSelectedOrgData, dispatch, form, orgNameInput]);

  const handleReset = () => {
    form.resetFields();
    if (currentPageNum === 1) updateTableData();
    else setcurrentPageNum(1);
  };

  useEffect(() => {
    // if (currentSelectedOrgData.orgCode) {
      updateTableData();
    // }
  }, [currentPageNum, currenPageSize, updateTableData]);

  useEffect(() => {
    if (treeData && treeData.length > 0 && currentSelectedOrgData) {
      nodePathArray = [];
      getNodeRoute(allTreeData, currentSelectedOrgData.id);

      setOrgPathList(nodePathArray.reverse());
    }
  }, [treeData, currentSelectedOrgData]);

  const handleCloseEdit = () => {
    setDrawerVisible(false);
    setCurrentEditData({});
  };

  const handleUpdate = () => {
    handleCloseEdit();
    location.reload();
    // if (onTreeRef.current) {
    //   const selected = onTreeRef.current.getSelected() || {};
    //   setCurrentSelectedOrgData({ ...selected });
    // }
  };

  const handleShowEdit = (type, level, record) => {
    if (type === 'edit') {
      setCurrentEditData(record);
    }
    setDrawerType(type);
    setDrawerVisible(true);
    if (currentSelectedOrgData) {
      setOrgAddOptParentId(currentSelectedOrgData[level === 'brother' ? 'parentId' : 'id']);
    }
  };

  const handlePositionManageVisible = (visible, record) => {
    if (record) setPosManageOrgId(record.id);
    setPositionVisible(visible);
  };

  const handleDel = (record) => {
    dispatch({
      type: 'orgManageModel/deleteOrg',
      payload: {
        orgId: record.id,
      },
    }).then((res) => {
      const { code, message: errMsg } = res;
      if (code === 0) {
        message.success('删除成功');
        // 删除最后一条数据判断
        if (orgSelectListTotal % currenPageSize === 1 && currentPageNum !== 1) {
          setcurrentPageNum(currentPageNum - 1 || 1);
        } else {
          updateTableData();
        }
        if (onTreeRef.current) {
          onTreeRef.current.deleteTreeNode(record);
        }
      } else {
        message.error(errMsg);
      }
    });
  };

  const handleGetChildrenData = (record, callback) => {
    dispatch({
      type: 'orgManageModel/getChildOrgListByParentId',
      payload: {
        parentId: record.id,
      },
    }).then((data) => {
      callback(data);
    });
  };

  const handleGoDetail = () => {
    history.push({
      pathname: '/authoritymanage/orgmanage/orgdetail',
      state: {
        orgDetailData: currentSelectedOrgData,
      },
    });
  };

  const handleTreeSelect = (selectedKeys, e, newTreeData) => {
    const current = e.node.props.data;
    setCurrentSelectedOrgData(current);
    allTreeData = newTreeData;
  };

  // const handleSearchInputChange = (e) => {
  //   setOrgNameInput(e.target.value);
  // };

  const handlePaginationChange = (page, pageSize) => {
    setcurrentPageNum(page);
    // setCurrenPageSize(pageSize);
  };

  const menu = (
    <Menu>
      <Menu.Item key="0">
        <a onClick={() => handleShowEdit('add', 'brother')}>同级组织</a>
      </Menu.Item>
      <Menu.Item key="1">
        <a onClick={() => handleShowEdit('add', 'son')}>下级组织</a>
      </Menu.Item>
    </Menu>
  );
  const columns = [
    {
      title: '组织 ID',
      dataIndex: 'id',
      key: 'id',
      textWrap: 'word-break',
      width: 100,
    },
    {
      title: '组织名称',
      dataIndex: 'orgName',
      key: 'orgName',
      textWrap: 'word-break',
      width: 150,
      fixed: 'left',
      render: (text) => (
        <Ellipsis length={20} tooltip fullWidthRecognition>
          {text}
        </Ellipsis>
      ),
    },
    {
      title: '组织编码',
      dataIndex: 'orgCode',
      key: 'orgCode',
      textWrap: 'word-break',
      width: 150,
      fixed: 'left',
      render: (text) => (
        <Ellipsis length={20} tooltip fullWidthRecognition>
          {text}
        </Ellipsis>
      ),
    },
    {
      title: '组织类型',
      dataIndex: 'orgType',
      key: 'orgType',
      width: 90,
      fixed: 'left',
      render: (text) => {
        const filteredList = ORG_TYPE_LIST.filter((item) => item.value === text);
        return filteredList.length > 0 ? filteredList[0].text : '';
      },
    },
    {
      title: '有效性',
      dataIndex: 'orgState',
      key: 'orgState',
      width: 80,
      fixed: 'left',
      render: (text) => (
        <span style={{ color: `${text === 1 ? '#1E8E3E' : '#999999'}` }}>
          ●{text === 0 ? '无效' : '有效'}
        </span>
      ),
    },
    {
      title: '父级组织',
      dataIndex: 'parentName',
      key: 'parentName',
      textWrap: 'word-break',
      width: 150,
      // fixed: 'left',
      render: (text) => (
        <Ellipsis length={20} tooltip fullWidthRecognition>
          {text}
        </Ellipsis>
      ),
    },
    {
      title: '岗位数',
      dataIndex: 'positionNum',
      key: 'positionNum',
      width: 80,
    },
    {
      title: '描述',
      dataIndex: 'orgDesc',
      key: 'orgDesc',
      width: 160,
      render: (text) => (
        <Ellipsis length={30} tooltip fullWidthRecognition>
          {text}
        </Ellipsis>
      ),
    },
    {
      title: '创建人',
      dataIndex: 'creatorName',
      key: 'creatorName',
      width: 90,
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreated',
      key: 'gmtCreated',
      width: 160,
    },
    {
      title: '更新人',
      dataIndex: 'modifierName',
      key: 'modifierName',
      width: 90,
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified',
      key: 'gmtModified',
      width: 160,
    },
    {
      title: '有效时间范围',
      dataIndex: 'expireStartTime',
      key: 'expireStartTime',
      width: 200,
      render: (text, record) => {
        const { expireStartTime, expireEndTime } = record;
        return `${expireStartTime} - ${expireEndTime || '永久'}`;
      },
    },
    {
      title: '数据来源',
      dataIndex: 'dataSource',
      key: 'dataSource',
      textWrap: 'word-break',
      width: 120,
      render: (text) => (
        <Ellipsis length={20} tooltip>
          {dataSourceEnum.find((item) => item.code === text)?.name || '未知数据来源'}
        </Ellipsis>
      ),
    },
    {
      title: '业务层级',
      dataIndex: 'businessLevel',
      key: 'businessLevel',
      textWrap: 'word-break',
      width: 120,
      render: (text) => (
        <Ellipsis length={20} tooltip>
          {businessLevelEnum.find((item) => item.code === text)?.name || '未知业务层级'}
        </Ellipsis>
      ),
    },
    {
      title: '部门分类',
      dataIndex: 'departmentClassification',
      key: 'departmentClassification',
      textWrap: 'word-break',
      width: 120,
      render: (text) => (
        <Ellipsis length={20} tooltip>
          {departmentClassificationEnum.find((item) => item.code === text)?.name || '未知部门分类'}
        </Ellipsis>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <div>
          <Button type="link" onClick={() => handlePositionManageVisible(true, record)}>
            岗位管理
          </Button>
          <Divider type="vertical" />
          <Button type="link" onClick={() => handleShowEdit('edit', 'self', record)}>
            编辑
          </Button>
          <Divider type="vertical" />
          <Popconfirm title="确定要删除该数据吗？" onConfirm={() => handleDel(record)}>
            <Button type="link">删除</Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  const handlePositionCloseEv = (isrefresh) => {
    if (isrefresh) updateTableData();
    handlePositionManageVisible(false);
  };

  return (
    <div className={styles.root}>
      <PageTopFormContent
        title="组织管理"
        content={
          <Form {...layout} form={form}>
            <Row gutter={[32, 16]}>
              <Col span={6}>
                <Form.Item name="orgName" label="组织名称">
                  <Input placeholder="请输入组织名称" />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name="orgCode" label="组织编码">
                  <Input placeholder="请输入组织编码" />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name="orgState" label="有效性">
                  <Select placeholder="请选择有效性" allowClear>
                    <Select.Option value="1">有效</Select.Option>
                    <Select.Option value="0">无效</Select.Option>
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name="orgType" label="分类">
                  <Select placeholder="请选择分类" allowClear>
                    {ORG_TYPE_LIST.map((item) => (
                      <Option key={item.value} value={item.value}>
                        {item.text}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={24} style={{ textAlign: 'right' }}>
                <Form.Item wrapperCol={{ span: 24 }}>
                  <Button type="primary" onClick={updateTableData}>
                    查询
                  </Button>
                  <Button style={{ marginLeft: 16 }} onClick={handleReset}>
                    重置
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        }
      />
      <div className={styles.bottomWrapper}>
        <div className={styles.leftTree}>
          <div className={styles.leftTreeTop}>
            <div className={styles.title}>组织列表</div>
            <div>
              {(!!currentSelectedOrgData?.id || currentSelectedOrgData?.id === 0) && (
                <>
                  <Button
                    type="link"
                    onClick={() => handleShowEdit('edit', 'brother', currentSelectedOrgData)}
                  >
                    编辑
                  </Button>
                  <Divider type="vertical" />
                </>
              )}
              <Dropdown overlay={menu} trigger={['click']} onClick={(e) => e.preventDefault()}>
                <Button type="link">
                  添加
                  <DownOutlined />
                </Button>
              </Dropdown>
            </div>
          </div>
          <Spin
            tip="加载中..."
            spinning={effects['orgManageModel/getOrgRootTree']}
            style={{ marginTop: 300 }}
          >
            {treeData && treeData.length > 0 && (
              <Tree
                treeData={treeData}
                getChildrenData={handleGetChildrenData}
                ref={onTreeRef}
                defaultSelectedKeys={[treeData && treeData.length > 0 ? treeData[0].key : '']}
                onSelect={handleTreeSelect}
                style={{ flex: 1, overflow: 'auto' }}
              />
            )}
          </Spin>
        </div>
        <div className={styles.rightTable}>
          <div className={styles.rightTableTop}>
            <div className={styles.left}>
              <div className={styles.title}>下级组织列表</div>
              <div className={styles.orgPath}>{orgPathList.join('>')}</div>
            </div>
            <div className={styles.right}>
              {!!currentSelectedOrgData?.id && (
                <>
                  <Button type="primary" onClick={handleGoDetail}>
                    组织详情
                  </Button>
                  <Button type="primary" onClick={() => handleShowEdit('add', 'son')}>
                    {' '}
                    <PlusOutlined />
                    添加组织
                  </Button>
                </>
              )}
            </div>
          </div>
          <div className={styles.tableWrapper}>
            <Table
              rowKey="id"
              loading={effects['orgManageModel/getOrgList']}
              columns={columns}
              dataSource={orgSelectList}
              pagination={false}
              scroll={{ x: 800 }}
            />
            <PaginationCommon
              total={orgSelectListTotal}
              onChange={handlePaginationChange}
              style={{ textAlign: 'right' }}
              current={currentPageNum}
              pageSize={currenPageSize}
            />
          </div>
        </div>
      </div>
      {drawerVisible && (
        <OrgAddEdit
          selectedOrgData={currentSelectedOrgData}
          editData={currentEditData}
          parentId={orgAddOptParentId}
          drawerType={drawerType}
          handleClose={handleCloseEdit}
          handleUpdate={handleUpdate}
        />
      )}
      {positionVisible && (
        <PositionManage
          orgId={posManageOrgId}
          drawerType={drawerType}
          handleClose={(isRefresh) => {
            handlePositionCloseEv(isRefresh);
          }}
        />
      )}
    </div>
  );
};

export default connect((state) => state)(OrgManage);
